package com.cha.chaCommon.core.intercepter;


import com.cha.chaCommon.core.annotation.NoLoginCheck;
import com.cha.chaCommon.core.exception.CustomerException;
import com.cha.chaCommon.core.utils.JwtUtils;
import com.cha.chaCommon.core.utils.UserUtils;

import io.jsonwebtoken.Claims;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/*
@Author  hkf
@date 2024/10/28
--轻舟已过万重山--
*/
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            boolean res = method.isAnnotationPresent(NoLoginCheck.class);
            if(res){
                return true;
            }
            String token = request.getHeader("Token");
            if(token==null || token.isEmpty()){
                throw new CustomerException("请重新登录!");
            }
            try {
                Claims claims = JwtUtils.parseJWT(token);
                Object uid = claims.get("uid");
                System.out.println(uid);

                //直接把用户id存到ThreadLocal
                UserUtils.setUid(Integer.valueOf(uid.toString()));
            }catch (Exception e){
                throw new CustomerException("无效Token");
            }

        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserUtils.removeUid();
    }
}
